package cn.edu.zust.se.service.user.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.edu.zust.se.api.clients.FileClient;
import cn.edu.zust.se.api.common.R;
import cn.edu.zust.se.api.entity.File;
import cn.edu.zust.se.api.entity.User;
import cn.edu.zust.se.api.entity.bo.FileBo;
import cn.edu.zust.se.api.entity.bo.UserBo;
import cn.edu.zust.se.api.entity.vo.UserVo;
import cn.edu.zust.se.service.user.service.UserService;
import cn.hutool.core.bean.BeanUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user")
@RequiredArgsConstructor
@Slf4j
public class UserController {
    private final UserService userService;
    private final FileClient fileClient;

    @GetMapping("/{id}")
    public R<UserVo> getUserById(@PathVariable Long id) {
        log.info(StpUtil.getLoginId().toString());
        return R.ok(userService.getUserById(id));
    }

    //获取当前登录用户的个人信息
    @GetMapping("/loginUserMsg")
    public R<UserVo> getUserInfo() {
        Long id = StpUtil.getLoginIdAsLong();
        return R.ok(userService.getUserById(id));
    }

    //用户登出
    @GetMapping("/logout")
    public R<Void> logout() {
        StpUtil.logout();
        return R.ok("已退出登录");
    }

    @PostMapping("/login")
    public R<UserVo> doLogin(@RequestBody UserBo bo) {
        UserVo userVo = userService.doLogin(bo);
        if (userVo != null) {
            userVo.setRootFolderId(fileClient.getRootFolderId(userVo.getId()).getData());
            return R.ok("登录成功", userVo);
        }
        return R.fail("账号或密码错误");
    }

    @PostMapping("/register")
    public R<Void> doRegister(@RequestBody UserBo bo) {
        Boolean success = userService.doRegister(bo);
        if (success) {
            return R.ok("注册成功");
        }
        return R.fail("用户名重复,注册失败");
    }

    //修改个人信息
    @PostMapping("/update")
    public R<Void> updateUserInfo(@RequestBody UserBo bo) {
        System.out.println(bo);
        bo.setId(StpUtil.getLoginIdAsLong());
        Boolean success = userService.updateUser(bo);
        if (success) {
            return R.ok();
        }
        return null;
    }

    //用户头像更新
    @PostMapping("/updateAvatar")
    public R<Void> updateAvatar(Long id) {
        User user = new User();
        user.setId(StpUtil.getLoginIdAsLong());
        user.setFileId(id);
        boolean b = userService.updateById(user);
        return b?R.ok():R.fail();
    }
}
